package com.xkstream.client.nim;

import android.content.Context;
import android.text.TextUtils;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.chatroom.ChatRoomService;
import com.netease.nimlib.sdk.chatroom.ChatRoomServiceObserver;
import com.netease.nimlib.sdk.chatroom.constant.MemberQueryType;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomInfo;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomData;
import com.netease.nimlib.sdk.chatroom.model.EnterChatRoomResultData;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;
import com.xkstream.client.application.Application;
import com.xkstream.client.entity.User;
import com.xkstream.client.utils.LogUtil;
import com.xkstream.client.utils.ProcessUtil;

import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Flowable;
import io.reactivex.functions.Consumer;

/**
 * Created by xiaoyi on 2017/5/23.
 */

public class NimHelper {
    private final static String vacationer_key = "nim_vacationer";
    private static String TAG = "NimHelper";
    /*角色*/
    public static final String CHARACTER_NORMAL = "NORMAL";  //普通
    public static final String CHARACTER_ADMIN = "ADMIN";    //管理员
    public static final String CHARACTER_ANCHOR = "ANCHOR";  //主播
    public static final String KEY_CHARACTER = "CHARACTER";  //主播


    private NimHelper() {
    }

    public static void init(Context context) {
        if (ProcessUtil.inMainProcess(context)) {
            NIMClient.init(context.getApplicationContext(), null, new SDKOptions());

            NIMClient.getService(MsgService.class).registerCustomAttachmentParser(new CustomAttachParser());
        }
    }


    public static void login(LoginInfo info) {
        NIMClient.getService(AuthService.class).login(info).setCallback(new RequestCallback() {
            @Override
            public void onSuccess(Object param) {
                LogUtil.e(TAG, "login success");
            }

            @Override
            public void onFailed(int code) {
                LogUtil.e(TAG, "login onFailed code " + code);
            }

            @Override
            public void onException(Throwable exception) {
                LogUtil.e(TAG, "login exception " + exception.getCause());
            }
        });
    }

    public static void login(LoginInfo info, RequestCallback callback) {
        WeakReference<RequestCallback> weakReference = new WeakReference<RequestCallback>(callback);
        NIMClient.getService(AuthService.class).login(info).setCallback(weakReference.get());
    }

    public static void logout() {
        NIMClient.getService(AuthService.class).logout();
    }

    public static void enterChatRoom(String roomId, EnterChatRoomCallback callback) {
        WeakReference<EnterChatRoomCallback> callbackWeakReference = new WeakReference<EnterChatRoomCallback>(callback);
        EnterChatRoomData data = new EnterChatRoomData(roomId);
        User user = Application.getUser();
        data.setNick(user.getExt_info().getNickname());
        data.setAvatar(user.getExt_info().getHead_icon());
        NIMClient.getService(ChatRoomService.class).enterChatRoom(data)
                .setCallback(new RequestCallback<EnterChatRoomResultData>() {
                    @Override
                    public void onSuccess(EnterChatRoomResultData param) {
                        if (callbackWeakReference.get() != null) {
                            callbackWeakReference.get().enterSuccess(param);
                        }
                    }

                    @Override
                    public void onFailed(int code) {

                        if (callbackWeakReference.get() != null) {
                            callbackWeakReference.get().enterFaild(code);
                        }
                    }

                    @Override
                    public void onException(Throwable exception) {
                        if (callbackWeakReference.get() != null) {
                            callbackWeakReference.get().enterException(exception);
                        }
                    }
                });
    }


    public static void exitChatRoom(String roomId) {
        NIMClient.getService(ChatRoomService.class).exitChatRoom(roomId);
    }

    public static void sendMessage(String roomId, ChatRoomMessage msg, SendMsgCallback callback) {
        WeakReference<SendMsgCallback> callbackWeakReference = new WeakReference<SendMsgCallback>(callback);
        NIMClient.getService(ChatRoomService.class).sendMessage(msg, false).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void param) {
                if (callbackWeakReference.get() != null)
                    callbackWeakReference.get().sendSuccess(msg);
            }

            @Override
            public void onFailed(int code) {
                if (callbackWeakReference.get() != null)
                    callbackWeakReference.get().sendFaild(code);
            }

            @Override
            public void onException(Throwable exception) {
                if (callbackWeakReference.get() != null)
                    callbackWeakReference.get().sendException(exception);
            }
        });
    }

    public static void registerMsgObserver(OnMessageReceiveListener listener, boolean registered) {
        WeakReference<OnMessageReceiveListener> weakReference = new WeakReference<OnMessageReceiveListener>(listener);
        Observer<List<ChatRoomMessage>> incomingChatRoomMsg = messages ->
                Flowable.fromIterable(messages)
                        .subscribe((message -> {
                            if (weakReference.get() != null)
                                weakReference.get().onReceive(message);
                        }));

        NIMClient.getService(ChatRoomServiceObserver.class)
                .observeReceiveMessage(incomingChatRoomMsg, registered);

    }

    /*更新信息*/
    public static void updateUserInfo(UserInfoFieldEnum key, Object value) {
        Map<UserInfoFieldEnum, Object> fields = new HashMap<>();
        fields.put(key, value);
        NIMClient.getService(UserService.class).updateUserInfo(fields);
    }

    /*获取聊天室成员列表*/
    public static void getChatRoomMember(String roomId, ChatRoomMemberListener listener) {
        WeakReference<ChatRoomMemberListener> reference = new WeakReference<ChatRoomMemberListener>(listener);
        NIMClient.getService(ChatRoomService.class).fetchRoomMembers(roomId,
                MemberQueryType.GUEST, 0, 1000)
                .setCallback(new RequestCallback<List<ChatRoomMember>>() {
                    @Override
                    public void onSuccess(List<ChatRoomMember> param) {
                        if (reference.get() != null)
                            reference.get().getMembers(param);
                    }

                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onException(Throwable exception) {

                    }
                });
    }

    /*获取聊天室成员列表*/
    public static void getChatRoomMember(String roomId, ChatRoomMemberListener listener, String ids) {
        WeakReference<ChatRoomMemberListener> reference = new WeakReference<ChatRoomMemberListener>(listener);
        NIMClient.getService(ChatRoomService.class).fetchRoomMembersByIds(roomId,
                Arrays.asList(ids))
                .setCallback(new RequestCallback<List<ChatRoomMember>>() {
                    @Override
                    public void onSuccess(List<ChatRoomMember> param) {
                        if (reference.get() != null)
                            reference.get().getMembers(param);
                    }

                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onException(Throwable exception) {

                    }
                });
    }

    /*获取聊天室成员列表*/
    public static void getChatRoomMember(int level, String roomId, ChatRoomMemberListener listener, String ids) {
        WeakReference<ChatRoomMemberListener> reference = new WeakReference<ChatRoomMemberListener>(listener);
        NIMClient.getService(ChatRoomService.class).fetchRoomMembersByIds(roomId,
                Arrays.asList(ids))
                .setCallback(new RequestCallback<List<ChatRoomMember>>() {
                    @Override
                    public void onSuccess(List<ChatRoomMember> param) {
                        if (reference.get() != null && !param.isEmpty()) {
                            param.get(0).setMemberLevel(level);
                            reference.get().getMembers(param);
                        }
                    }

                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onException(Throwable exception) {

                    }
                });
    }

    public static void queryChatRoomInfo(String roomId) {
        NIMClient.getService(ChatRoomService.class)
                .fetchRoomInfo(roomId).setCallback(new RequestCallback<ChatRoomInfo>() {
            @Override
            public void onSuccess(ChatRoomInfo param) {
                LogUtil.e(TAG, param.toString());
            }

            @Override
            public void onFailed(int code) {
                LogUtil.e(TAG, code + "");
            }

            @Override
            public void onException(Throwable exception) {
                LogUtil.e(TAG, exception.toString());
            }
        });
    }

}
